#pragma once
#include <iostream>
#include <string>
#include <fstream> // C++文件操作头文件
#include <unordered_map>
#include "Log.hpp"
#include "Common.hpp"

const std::string gpath = "./";
const std::string gdictname = "dict.txt";
const std::string gstep = ": ";

using namespace LogMudule;

class Dictionary
{
private:
    // 加载字典
    bool LoadDictionary()
    {
        std::string file = _path + _filename;
        // 文件操作
        std::ifstream in(file.c_str());
        if (!in.is_open())
        {
            LOG(LogLevel::ERROR) << "open file " << file << " error";
            return false;
        }

        std::string line;
        while (std::getline(in, line))
        {
            // happy: 快乐的
            std::string key;
            std::string value;
            if (SplitString(line, &key, &value, gstep))
            { // 把KV结构数据插入到hash
                _dictionary.insert(std::make_pair(key, value));
            }
        }
        in.close(); // 文件关闭
        return true;
    }
public:
    Dictionary(const std::string &path = gpath, const std::string &filename = gdictname)
        : _path(path)
        , _filename(filename)
    {
        LoadDictionary();
    }

    std::string Translate(const std::string &word)
    {
        auto iter = _dictionary.find(word);
        if(iter == _dictionary.end())   return "None";
        return iter->second;
    }
    ~Dictionary()
    {
    }
private:
    std::unordered_map<std::string, std::string> _dictionary;
    std::string _path;
    std::string _filename;
};